package cn.micai.base.concurrent;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * 描述：以ArrayBlockingQueue 为例写一个程序，表示生产者-消费者问题。生产者向
 阻塞队列中放入字符，消费者从阻塞队列中移除字符。
 * <p>
 *
 * @author: 赵新国
 * @date: 2018/5/14 13:56
 */
public class BlockingQueueDemo {

    public static void main(String [] args) {
        BlockingQueue<String> queue = new ArrayBlockingQueue<String>(5);
        Producer producer = new Producer(queue);
        Consumer c1 = new Consumer(queue);
        Consumer c2 = new Consumer(queue);
        new Thread(producer).start();
        new Thread(c1).start();
        new Thread(c2).start();
    }

    // 生产者
    private static class Producer implements Runnable {

        private final BlockingQueue<String> queue;

        Producer(BlockingQueue<String> queue) {
            this.queue = queue;
        }

        @Override
        public void run() {
            for (int i=0; i<100; i++) {
                try {
                    queue.put(produce());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

        public String produce() {
            String temp = "" + (char)('A'+(int)(Math.random()*26));
            System.out.println("produce: " + temp);
            return temp;
        }
    }

    // 消费者
    private static class Consumer implements Runnable {

        private final BlockingQueue<String> queue;

        Consumer(BlockingQueue<String> queue) {
            this.queue = queue;
        }

        @Override
        public void run() {
            try {
                for (int i=0; i<100; i++) {
                    consume(queue.take());
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        public void consume(String x) {
            System.out.println("consume: " + x);
        }
    }
}

